﻿using DataAccess.DTO;
using LogUtility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Web;
using System.Web.Http.Filters;

namespace Api.App_Start
{
    public class ExceptionFilter : ExceptionFilterAttribute
    {
        private HttpResponseMessage GetResponse(bool state, string message)
        {
            var resultModel = new Result() { State = state, Message = message };

            return new HttpResponseMessage()
            {
                Content = new ObjectContent<Result>(
                    resultModel,
                    new JsonMediaTypeFormatter(),
                    "application/json"
                    )
            };
        }

        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            var code = -1;
            var message = "出现错误";

            //if (actionExecutedContext.Exception is UserDisplayException)
            //{
            //    message = actionExecutedContext.Exception.Message;
            //}
            //if (actionExecutedContext.Exception is UserLoginException)
            //{
            //    code = -2;
            //    message = actionExecutedContext.Exception.Message;
            //}

            if (actionExecutedContext.Response == null)
            {
                actionExecutedContext.Response = GetResponse(false, message);
            }

            //记录错误日志
            LogHelper.Error("出现错误", actionExecutedContext.Exception);

            base.OnException(actionExecutedContext);
        }

    }
}